const WXAPI = require('../../wxapi/main')
const app = getApp()
Page({
    data: {
        goodsList: {
            saveHidden: true,
            totalPrice: 0,
            totalScoreToPay: 0,
            allSelect: true,
            noSelect: false,
            list: [],
          brokerage:0
        },
        delBtnWidth: 120, //删除按钮宽度单位（rpx）
    },
    //事件处理函数
    swiperchange: function(e) {
        //console.log(e.detail.current)
        this.setData({
            swiperCurrent: e.detail.current
        })
    },
    toDetailsTap: function(e) {
        wx.navigateTo({
            url: "/pages/goods-details/index?id=" + e.currentTarget.dataset.id
        })
    },

    //获取元素自适应后的实际宽度
    getEleWidth: function(w) {
        var real = 0;
        try {
            var res = wx.getSystemInfoSync().windowWidth;
            var scale = (750 / 2) / (w / 2); //以宽度750px设计稿做宽度的自适应
            // console.log(scale);
            real = Math.floor(res / scale);
            return real;
        } catch (e) {
            return false;
            // Do something when catch error
        }
    },
    initEleWidth: function() {
        var delBtnWidth = this.getEleWidth(this.data.delBtnWidth);
        this.setData({
            delBtnWidth: delBtnWidth
        });
    },
    onLoad: function() {
        // var that = this;
        // // 购物车商品获取
        // wx.request({
        //   // url: 'http://3s.dkys.org:25333/api/banner/list',
        //   url: 'https://www.brvpmusic.com/api/shoppingTrolley/getList',
        //   method: 'GET',
        //   data: {
        //     'openid': wx.getStorageSync('OpenId')
        //   },
        //   header: {
        //     'Content-Type': 'application/json'
        //   },
        //   success: function (res) {
        //     console.log('购物车商品获取成功');
        //     console.log(res.data)
        //     // that.setData({
        //     //   'mygoods': res.data.body,
        //     // })
        //   },
        //   fail: function (res) {
        //     console.log('返回失败');
        //   }
        // })
        this.initEleWidth();
        this.onShow();
    },
    onShow: function() {

        var shopList = [];
        // 获取购物车数据
        this.shoppingTrolleyGetList()


        var shopCarInfoMem = wx.getStorageSync('shopCarInfo');
        if (shopCarInfoMem && shopCarInfoMem.shopList) {
            shopList = shopCarInfoMem.shopList
        }
        console.log(shopList, 86)
            // this.data.goodsList.list = shopList;
            // this.setGoodsList(this.getSaveHide(), this.totalPrice(), this.allSelect(), this.noSelect(), shopList);
    },
    // 获取购物车数据
    shoppingTrolleyGetList() {
        var that = this
        wx.request({
            url: 'https://www.brvpmusic.com/api/shoppingTrolley/getList',
            // url: 'https://www.brvpmusic.com/api/products/getList',
            data: {
                'openid': wx.getStorageSync('OpenId')
            },
            method: 'GET',
            header: {
                'Content-Type': 'application/json'
            },
            success: function(res) {
                console.log('购物车数据获取成功');
                console.log(res.data);
                if (res.data.status) {
                    var shopList = that.bulidShopCarInfo(res.data.body)
                    console.log(shopList, 109)
                    that.data.goodsList.list = shopList;
                    that.setGoodsList(that.getSaveHide(), that.totalPrice(), that.allSelect(), that.noSelect(), shopList);
                }

            },
            fail: function(res) {
                console.log('返回失败');
            }
        })
    },
    /**
     * 组建购物车信息
     */
    bulidShopCarInfo(body) {
        var list = []
        body.forEach(element => {
            list.push({
                active: false,
                commission: element.commission,
                goodsId: element.products ? element.products.pPid : '',
                label: element.spec,
                brokerage: element.brokerage,
                left: '',
                name: element.goodsName,
                number: element.sNum,
                pIsintegral: element.integral,
                pic: 'https://www.brvpmusic.com' + element.productImg,
                price: element.price,
                propertyChildIds: '',
                sid: element.sId,
                score: element.commission,
            })
        });
        return list;
    },
    toIndexPage: function() {
        wx.switchTab({
            url: "/pages/index/index"
        });
    },

    touchS: function(e) {
        if (e.touches.length == 1) {
            this.setData({
                startX: e.touches[0].clientX
            });
        }
    },
    touchM: function(e) {
        var index = e.currentTarget.dataset.index;

        if (e.touches.length == 1) {
            var moveX = e.touches[0].clientX;
            var disX = this.data.startX - moveX;
            var delBtnWidth = this.data.delBtnWidth;
            var left = "";
            if (disX == 0 || disX < 0) { //如果移动距离小于等于0，container位置不变
                left = "margin-left:0px";
            } else if (disX > 0) { //移动距离大于0，container left值等于手指移动距离
                left = "margin-left:-" + disX + "px";
                if (disX >= delBtnWidth) {
                    left = "left:-" + delBtnWidth + "px";
                }
            }
            var list = this.data.goodsList.list;
            if (index != "" && index != null) {
                list[parseInt(index)].left = left;
                this.setGoodsList(this.getSaveHide(), this.totalPrice(), this.allSelect(), this.noSelect(), list);
            }
        }
    },

    touchE: function(e) {
        var index = e.currentTarget.dataset.index;
        if (e.changedTouches.length == 1) {
            var endX = e.changedTouches[0].clientX;
            var disX = this.data.startX - endX;
            var delBtnWidth = this.data.delBtnWidth;
            //如果距离小于删除按钮的1/2，不显示删除按钮
            var left = disX > delBtnWidth / 2 ? "margin-left:-" + delBtnWidth + "px" : "margin-left:0px";
            var list = this.data.goodsList.list;
            if (index !== "" && index != null) {
                list[parseInt(index)].left = left;
                this.setGoodsList(this.getSaveHide(), this.totalPrice(), this.allSelect(), this.noSelect(), list);

            }
        }
    },
    //左滑删除单个商品
    delItem: function(e) {
        var index = e.currentTarget.dataset.index;
        var sId =e.currentTarget.dataset.id;
        var list = this.data.goodsList.list;
        console.log("sId="+sId);
        //刪除缓存
        list.splice(index, 1);
        this.setGoodsList(this.getSaveHide(), this.totalPrice(), this.allSelect(), this.noSelect(), list);
        //调用删除接口
        wx.showLoading();
        var that = this
        var params = {
            sId: sId,
            openid: wx.getStorageSync('OpenId')
        }
        wx.request({
            url: 'https://www.brvpmusic.com/api/shoppingTrolley/delete',
            // url: 'http://3s.dkys.org:25333/api/shoppingTrolley/delete',
            data: params,

            method: 'POST',
            header: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            success: function(res) {
                wx.hideLoading()
                console.log('返回成功');
                console.log(res.data);
                that.shoppingTrolleyGetList()

            },
            fail: function(res) {
                wx.hideLoading()
                console.log('返回失败');
            }
        })
    },
    selectTap: function(e) {
        var index = e.currentTarget.dataset.index;
        var list = this.data.goodsList.list;
        if (index !== "" && index != null) {
            list[parseInt(index)].active = !list[parseInt(index)].active;
            this.setGoodsList(this.getSaveHide(), this.totalPrice(), this.allSelect(), this.noSelect(), list);
        }
    },
    totalPrice: function() {
        var list = this.data.goodsList.list;
        var total = 0;
        let totalScoreToPay = 0;
        for (var i = 0; i < list.length; i++) {
            var curItem = list[i];
            if (curItem.active) {
                total += parseFloat(curItem.price) * curItem.number;
                totalScoreToPay += curItem.score * curItem.number;
            }
        }
        this.data.goodsList.totalScoreToPay = totalScoreToPay;
        total = parseFloat(total.toFixed(2)); //js浮点计算bug，取两位小数精度
        return total;
    },
    allSelect: function() {
        var list = this.data.goodsList.list;
        var allSelect = false;
        for (var i = 0; i < list.length; i++) {
            var curItem = list[i];
            if (curItem.active) {
                allSelect = true;
            } else {
                allSelect = false;
                break;
            }
        }
        return allSelect;
    },
    noSelect: function() {
        var list = this.data.goodsList.list;
        var noSelect = 0;
        for (var i = 0; i < list.length; i++) {
            var curItem = list[i];
            if (!curItem.active) {
                noSelect++;
            }
        }
        if (noSelect == list.length) {
            return true;
        } else {
            return false;
        }
    },
    setGoodsList: function(saveHidden, total, allSelect, noSelect, list) {
        this.setData({
            goodsList: {
                saveHidden: saveHidden,
                totalPrice: total,
                allSelect: allSelect,
                noSelect: noSelect,
                list: list,
                totalScoreToPay: this.data.goodsList.totalScoreToPay
            }
        });
        var shopCarInfo = {};
        var tempNumber = 0;
        shopCarInfo.shopList = list;
        for (var i = 0; i < list.length; i++) {
            tempNumber = tempNumber + list[i].number
        }
        shopCarInfo.shopNum = tempNumber;
        wx.setStorage({
            key: "shopCarInfo",
            data: shopCarInfo
        })
    },
    bindAllSelect: function() {
        var currentAllSelect = this.data.goodsList.allSelect;
        var list = this.data.goodsList.list;
        if (currentAllSelect) {
            for (var i = 0; i < list.length; i++) {
                var curItem = list[i];
                curItem.active = false;
            }
        } else {
            for (var i = 0; i < list.length; i++) {
                var curItem = list[i];
                curItem.active = true;
            }
        }

        this.setGoodsList(this.getSaveHide(), this.totalPrice(), !currentAllSelect, this.noSelect(), list);
    },
    jiaBtnTap: function(e) {
        var that = this
        var index = e.currentTarget.dataset.index;
        var index = e.currentTarget.dataset.index;
        var list = this.data.goodsList.list;
        if (index !== "" && index != null) {
            if (list[parseInt(index)].number < 999) {
                wx.showLoading()
                list[parseInt(index)].number++
                    let params = {
                        openid: wx.getStorageSync('OpenId'),
                        sId: list[parseInt(index)].sid,
                        sNum: list[parseInt(index)].number,
                    }
                console.log(params, 335)
                wx.request({
                    // url: 'https://www.brvpmusic.com/api/shoppingTrolley/edit',
                    url: 'https://www.brvpmusic.com/api/shoppingTrolley/edit',
                    data: params,
                    method: 'GET',
                    header: {
                        'Content-Type': 'application/json'
                    },
                    success: function(res) {
                        wx.hideLoading()
                        console.log('购物车数据获取成功');
                        console.log(res.data);
                        if (res.data.status) {
                            that.shoppingTrolleyGetList()
                        }

                    },
                    fail: function(res) {
                        wx.hideLoading()
                        console.log('返回失败');
                    }
                })
            }
        }
        // var list = that.data.goodsList.list;
        // if (index !== "" && index != null) {
        //   // 添加判断当前商品购买数量是否超过当前商品可购买库存
        //   var carShopBean = list[parseInt(index)];
        //   var carShopBeanStores = 0;
        //   WXAPI.goodsDetail(carShopBean.goodsId).then(function(res) {
        //     console.log(res.data)
        //     carShopBeanStores = res.data.basicInfo.stores;
        //     if (list[parseInt(index)].number < carShopBeanStores) {
        //       list[parseInt(index)].number++;
        //       that.setGoodsList(that.getSaveHide(), that.totalPrice(), that.allSelect(), that.noSelect(), list);
        //     }
        //     that.setData({
        //       curTouchGoodStore: carShopBeanStores
        //     })
        //   })
        // }
    },
    jianBtnTap: function(e) {
        var index = e.currentTarget.dataset.index;
        var list = this.data.goodsList.list;
        if (index !== "" && index != null) {
            if (list[parseInt(index)].number > 1) {
                var that = this
                wx.showLoading()
                list[parseInt(index)].number--
                    let params = {
                        openid: wx.getStorageSync('OpenId'),
                        sId: list[parseInt(index)].sid,
                        sNum: list[parseInt(index)].number,
                    }
                console.log(params, 335)
                wx.request({
                    // url: 'https://www.brvpmusic.com/api/shoppingTrolley/edit',
                    url: 'https://www.brvpmusic.com/api/shoppingTrolley/edit',
                    data: params,
                    method: 'GET',
                    header: {
                        'Content-Type': 'application/json'
                    },
                    success: function(res) {
                        wx.hideLoading()
                        console.log('购物车数据获取成功');
                        console.log(res.data);
                        if (res.data.status) {
                            that.shoppingTrolleyGetList()
                        }

                    },
                    fail: function(res) {
                        wx.hideLoading()
                        console.log('返回失败');
                    }
                })
            }
        }
    },
    editTap: function() {
        var list = this.data.goodsList.list;
        for (var i = 0; i < list.length; i++) {
            var curItem = list[i];
            curItem.active = false;
        }
        this.setGoodsList(!this.getSaveHide(), this.totalPrice(), this.allSelect(), this.noSelect(), list);
    },
    saveTap: function() {
        var list = this.data.goodsList.list;
        for (var i = 0; i < list.length; i++) {
            var curItem = list[i];
            curItem.active = true;
        }
        this.setGoodsList(!this.getSaveHide(), this.totalPrice(), this.allSelect(), this.noSelect(), list);
    },
    getSaveHide: function() {
        var saveHidden = this.data.goodsList.saveHidden;
        return saveHidden;
    },
    deleteSelected: function() {
        wx.showLoading()
        var that = this
        var list = this.data.goodsList.list;
        /*
         for(let i = 0 ; i < list.length ; i++){
               let curItem = list[i];
               if(curItem.active){
                 list.splice(i,1);
               }
         }
         */
        // above codes that remove elements in a for statement may change the length of list dynamically
        var deletelist = list.filter(function(curGoods) {
            return curGoods.active;
        });
        var sidlist = deletelist.map((item) => {
            return item.sid
        })
        console.log(sidlist, 370)
        var params = {
            sId: sidlist,
            openid: wx.getStorageSync('OpenId')
        }
        console.log(params, 370)
        wx.request({
            url: 'https://www.brvpmusic.com/api/shoppingTrolley/delete',
            // url: 'http://3s.dkys.org:25333/api/shoppingTrolley/delete',
            data: params,

            method: 'POST',
            header: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            success: function(res) {
                wx.hideLoading()
                console.log('返回成功');
                console.log(res.data);
                that.shoppingTrolleyGetList()

            },
            fail: function(res) {
                wx.hideLoading()
                console.log('返回失败');
            }
        })

        // list = list.filter(function(curGoods) {
        //     return !curGoods.active;
        // });
        // this.setGoodsList(this.getSaveHide(), this.totalPrice(), this.allSelect(), this.noSelect(), list);
    },
    toPayOrder: function() {
        // var that = this;
        // // 提交订单
        // wx.request({
        //   url: 'https://www.brvpmusic.com/api/orderProduct/submitOrder',
        //   // url: con.index_mybanners,
        //   data: {
        //     "shoppingTrolleyList": [
        //       {
        //         "products": {
        //           "pPid": 48
        //         },
        //         "aids": [323, 326],
        //         "sNum": 100
        //       }
        //     ],
        //     "customer": {
        //       "openid": "5"
        //     },
        //     "oAddress": "东华理工大学,枫林大道",
        //     "oLeavemessage": "物流快点",
        //     "oTelephone": "12345678910",
        //     "oDeliveryname": "肥仔快乐"
        //   },

        //   method: 'POST',
        //   header: {
        //     'Content-Type': 'application/json'
        //   },
        //   success: function (res) {
        //     console.log('返回成功');
        //     console.log(res.data);

        //     // that.setData({
        //     //   mybanners: res.data.data,
        //     // })
        //   },
        //   fail: function (res) {
        //     console.log('返回失败');
        //   }
        // })
        wx.showLoading();
        var that = this;
        if (this.data.goodsList.noSelect) {
            wx.hideLoading();
            return;
        }
        // 重新计算价格，判断库存
        var shopList = [];
        var shopCarInfoMem = wx.getStorageSync('shopCarInfo');
        if (shopCarInfoMem && shopCarInfoMem.shopList) {
            // shopList = shopCarInfoMem.shopList
            shopList = shopCarInfoMem.shopList.filter(entity => {
                return entity.active;
            });
        }
      var brokerageList = shopList.map((item) => {
        return item.brokerage
      })
      console.log("brokerageList-----" + brokerageList);
      that.setData({
        brokerage: brokerageList
      });
        if (shopList.length == 0) {
            wx.hideLoading();
            return;
        }
        var isFail = false;
        var doneNumber = 0;
        var needDoneNUmber = shopList.length;
        for (let i = 0; i < shopList.length; i++) {
            if (isFail) {
                wx.hideLoading();
                return;
            }
            let carShopBean = shopList[i];
            // // 获取价格和库存
            // if (!carShopBean.propertyChildIds || carShopBean.propertyChildIds == "") {
            //   WXAPI.goodsDetail(carShopBean.goodsId).then(function(res) {
            //     doneNumber++;
            //     if (res.data.properties) {
            //       wx.showModal({
            //         title: '提示',
            //         content: res.data.basicInfo.name + ' 商品已失效，请重新购买',
            //         showCancel: false
            //       })
            //       isFail = true;
            //       wx.hideLoading();
            //       return;
            //     }
            //     if (res.data.basicInfo.stores < carShopBean.number) {
            //       wx.showModal({
            //         title: '提示',
            //         content: res.data.basicInfo.name + ' 库存不足，请重新购买',
            //         showCancel: false
            //       })
            //       isFail = true;
            //       wx.hideLoading();
            //       return;
            //     }
            //     if (res.data.basicInfo.minPrice != carShopBean.price) {
            //       wx.showModal({
            //         title: '提示',
            //         content: res.data.basicInfo.name + ' 价格有调整，请重新购买',
            //         showCancel: false
            //       })
            //       isFail = true;
            //       wx.hideLoading();
            //       return;
            //     }
            //     if (needDoneNUmber == doneNumber) {
            //       that.navigateToPayOrder();
            //     }
            //   })
            // } else {
            //   WXAPI.goodsPrice({
            //     goodsId: carShopBean.goodsId,
            //     propertyChildIds: carShopBean.propertyChildIds
            //   }).then(function(res) {
            //     doneNumber++;
            //     if (res.data.stores < carShopBean.number) {
            //       wx.showModal({
            //         title: '提示',
            //         content: carShopBean.name + ' 库存不足，请重新购买',
            //         showCancel: false
            //       })
            //       isFail = true;
            //       wx.hideLoading();
            //       return;
            //     }
            //     if (res.data.price != carShopBean.price) {
            //       wx.showModal({
            //         title: '提示',
            //         content: carShopBean.name + ' 价格有调整，请重新购买',
            //         showCancel: false
            //       })
            //       isFail = true;
            //       wx.hideLoading();
            //       return;
            //     }
            //     if (needDoneNUmber == doneNumber) {
            //       that.navigateToPayOrder();
            //     }
            //   })
            // }
            that.navigateToPayOrder();
        }
    },
    navigateToPayOrder: function() {
        wx.hideLoading();
        wx.navigateTo({
          url: "/pages/to-pay-order/index?&brokerage=" + this.data.brokerage
        })
    }



})